<!-- 姓氏谐音卡通情侣 -->
<template>
  <hm-layout>
    <view class="avatar-container">
      <view class="avatar-show">
        <image class="bg" :src="templateData.currentBg" :style="{ width: `${customSize}px`, height: `${customSize}px` }">
        </image>
        <image class="person" v-if="currentPerson" :src="currentPerson"
          :style="{ width: `${customSize}px`, height: `${customSize}px` }"></image>
        <homophonic-word v-drag="{ maxX: customSize, maxY: customSize }" :style="{ fontSize: customSize / 30 + 'px' }"
          v-if="templateData.componentClass === 1 || templateData.componentClass === 2" :templateData="templateData"
          :manName="manName" :femaleName="femaleName" :font="currentFont" />
        <view class="watermark" v-if="!isVip" :style="{ top: (customSize - 60) + 'px' }">海米AI</view>
      </view>
      <el-slider :max="1024" :min="500" v-model="customSize" vertical :height="customSize + 'px'" />
      <view class="avatar-info">
        <view class="name-editor">
          <el-input :size="customSize > 750 ? 'large' : 'normal'" style="color: #565656" class="input-box operate"
            placeholder="请输入姓氏" v-model="inputs.name1" />
          <el-input :size="customSize > 750 ? 'large' : 'normal'" style="color: #565656" class="input-box operate"
            placeholder="请输入姓氏" v-model="inputs.name2" />
          <el-button :size="customSize > 750 ? 'large' : 'normal'" type="primary" class="operate"
            @click="getName">生成</el-button>
          <el-button :size="customSize > 750 ? 'large' : 'normal'" type="primary" class="operate"
            @click="bugVip">去水印</el-button>
        </view>
        <el-scrollbar style="height: 140px;">
          <view class="scrollbar-flex-content">
            <view v-for="(person, index) in templateData.mainBgList"
              :class="`${person.src === currentPerson ? 'acitve' : ''}`" :key="index" @click="selectPerson(person.src)">
              <image :lazy-load="true" :src="person.src" class="picker-item" />
              <view class="name">{{ person.title }}</view>
            </view>
          </view>
        </el-scrollbar>
        <el-form>
          <view class="flex flex-column">
            <el-form-item label="底图">
              <uniImageUpload :height="100" :width="100" v-model="templateData.currentBg"></uniImageUpload>
            </el-form-item>
            <el-form-item label="字体颜色">
              <el-color-picker v-model="templateData.homophonicWordColor"></el-color-picker>
            </el-form-item>
            <view class="flex">
              <el-form-item label="男词bg:">
                <uniImageUpload :height="50" :width="50" v-model="templateData.manWordBg"></uniImageUpload>
              </el-form-item>
              <el-form-item style="margin-left: 20px;" label="女词bg:">
                <uniImageUpload :height="50" :width="50" v-model="templateData.femaleWordBg"></uniImageUpload>
              </el-form-item>
            </view>
            <font-picker-pc v-model="currentFont" />
          </view>
        </el-form>
      </view>
      <view class="avatar-edit">

        <view class="publish-wrap_inner-container">
          <el-form label-width="80px">

            <el-form-item label="主图列表">
              <uploadMainBg :mainBgList="templateData.mainBgList" />
            </el-form-item>
          </el-form>
        </view>
      </view>
    </view>
    <VipPopup @paysuccess="paySuccess" :config="pageConfig.price_config"
      :tool-info="{ name: pageConfig.tool_name, desc: pageConfig.tool_desc }" :tool-id="toolId" v-model="vipIsShow" />
  </hm-layout>
</template>

<script setup>
import {
  ref,
  computed,
  onBeforeMount,
  onMounted
} from 'vue'
import {
  onLoad,
  onShareAppMessage
} from '@dcloudio/uni-app';
import {
  manDefaultNameList,
  femaleDefaultNameList
} from './common-tem-config.js'
// import bgPicker from '@/common/components/pickers/bg-picker.vue';
// import fontPicker from '@/common/components/pickers/font-picker.vue';
// import personPicker from '@/common/components/pickers/person-picker.vue';
// import canvasDrawer from "@/common/components/canvas-drawer/index.vue";
// import hmFooter from '@/common/components/hm-footer/hm-footer.vue';
import homophonicWord from './homophonic-word-top.vue'
import uniImageUpload from '/common/components/UniImageUpload'
import uploadMainBg from './uploadMainBg.vue'
import VipPopup from '@/common/components/hm-vip-popup/index.vue';
import fontPickerPc from '@/common/components/pickers/font-picker-pc.vue'
const vk = uni.vk;
const baseUrl = vk.getVuex('$app.config.staticUrl.baseUrl');

let customSize = ref(500);
let isVip = ref(false);
const toolId = 'custom-avatar';
const pageConfig = ref({
  tool_name: "姓氏头像直播工具",
  tool_desc: "告别PS手工切换，助您高效直播!",
  price_config: []
})
let vipIsShow = ref(false)


const currentFont = ref('qinzi');
const currentPerson = ref('')

const inputs = ref({
  name1: '',
  name2: ''
})
let templateData = ref({
  currentBg: baseUrl + '/avatar-client/bgs/1.jpg',
  componentClass: 2,
  femaleWordBg: "https://mp-f94b3c95-ea57-45eb-aad5-8365caef5925.cdn.bspapp.com/cloudstorage/00b9a265-9580-47d8-9e62-eb26c53785ab.png",
  homophonicWordColor: "#75221D",
  manWordBg: "https://mp-f94b3c95-ea57-45eb-aad5-8365caef5925.cdn.bspapp.com/2023/10/21/81829944-29963847-D.png",
  mainBgList: [{
    "src": "https://mp-f94b3c95-ea57-45eb-aad5-8365caef5925.cdn.bspapp.com/2023/10/21/93009506-86736459-2.png",
    "title": ""
  },
  {
    "src": "https://mp-f94b3c95-ea57-45eb-aad5-8365caef5925.cdn.bspapp.com/2023/10/21/93669396-74816517-3.png",
    "title": ""
  },
  {
    "src": "https://mp-f94b3c95-ea57-45eb-aad5-8365caef5925.cdn.bspapp.com/2023/10/21/93679151-25639195-1.png",
    "title": ""
  },
  {
    "src": "https://mp-f94b3c95-ea57-45eb-aad5-8365caef5925.cdn.bspapp.com/2023/10/21/93685718-18582212-5.png",
    "title": ""
  },
  {
    "src": "https://mp-f94b3c95-ea57-45eb-aad5-8365caef5925.cdn.bspapp.com/2023/10/21/93691558-93549338-4.png",
    "title": ""
  }
  ]
});
const hasGenerate = ref(false)
const isAllow = ref(false)

const manName = ref(manDefaultNameList[0])
const manNameList = ref(manDefaultNameList)
const femaleName = ref(femaleDefaultNameList[0])
const femaleNameList = ref(femaleDefaultNameList);

const nameSelectList = computed(() => {
  const man = manNameList.value.map(i => ({
    label: i.Name,
    value: i.Index
  }));
  const female = femaleNameList.value.map(i => ({
    label: i.Name,
    value: i.Index
  }));
  return [man, female];
})

const selectName = (e) => {
  const [man, female] = e;
  manName.value = {
    Name: man.label,
    Index: man.value
  };
  femaleName.value = {
    Name: female.label,
    Index: female.value
  };

  namePickerVisible.value = false;
}

const getName = async () => {
  if (!inputs.value.name1 || !inputs.value.name2) {
    return
  }
  let names = {
    names1: [],
    names2: []
  };
  try {
    let res = await vk.callFunction({
      url: 'client/template/pub/getIdiom',
      title: '',
      data: {
        name1: inputs.value.name1,
        name2: inputs.value.name2,
      }
    })
    if (res && res.data) {
      names.names1 = JSON.parse(vk.myfn.HmUtils.Crypto.decrypt(res.data.name1));
      names.names2 = JSON.parse(vk.myfn.HmUtils.Crypto.decrypt(res.data.name2));

      manNameList.value = names.names1;
      manName.value = names.names1[0];

      femaleNameList.value = names.names2;
      femaleName.value = names.names2[0];
    }
  } catch (err) {
  }

}


const generateSuccess = (e) => {
  console.log('generateSuccess', e.names1, e.names2);
  if (!e || !e.names1 || !e.names2) {
    vk.toast('抱歉，暂未支持该姓氏，我们会努力改进的！');
  }

  manNameList.value = e.names1;
  manName.value = e.names1[0];

  femaleNameList.value = e.names2;
  femaleName.value = e.names2[0];
  hasGenerate.value = true;

}

const generateFail = (e) => {
  vk.toast(e)
}
let selectPerson = (person) => {
  currentPerson.value = person;
}

const bugVip = async () => {
  isVip.value = await checkVip();
  if (!isVip.value) {
    vipIsShow.value = true;
    return;
  }
}

const paySuccess = async () => {
  isVip.value = await checkVip();
}

const checkVip = () => {
  return new Promise((resolve, reject) => {
    vk.callFunction({
      url: 'user/kh/getMyToolInfos',
      title: '请求中...',
      data: {},
      success: (res) => {
        const toolInfoList = res.toolInfo;
        if (!toolInfoList || !toolInfoList.length) {
          resolve(false);
        } else {
          // 过滤当前tool_id且未过期
          const tool = toolInfoList.find(item => (item.tool_id === toolId && !item.vipExpire));
          resolve(!!tool);
        }
      },
      fail() {
        resolve(false);
      }
    });
  })
}

onBeforeMount(async () => {
  vk.callFunction({
    url: 'ai-client/common/pub/getConfig',
    title: '请求中...',
    data: {},
    success: (res) => {
      const toolConfig = res.data.find(conf => conf.tool_id === toolId);
      console.log('toolConfig', toolConfig, res.data);
      pageConfig.value = toolConfig || {};
    }
  });
})

onMounted(async () => {
  isVip.value = await checkVip();
  currentPerson.value = templateData.value.mainBgList[0].src || ''
  uni.loadFontFace({
    global: true,
    family: 'qinzi',
    source: `url("https://mp-6311ccac-218f-4072-bf34-9cd284ea3029.cdn.bspapp.com/avatar-client/font/qinzi.ttf")`,
    success: () => {
      console.log(`加载字体qinzi成功`);
    },
    fail(e) {
      console.log('加载字体失败')
    },
    scopes: ["webview", "native"],
  })
})

</script>

<style lang="scss" scoped>
.avatar-container {
  position: relative;
  width: 100%;
  margin: 10px;
  display: flex;

  .flex {
    display: flex;
  }

  .avatar-show {
    // width: 500px;
    // height: 500px;
    transform-origin: 0 0;
    position: relative;

    .watermark {
      position: absolute;
      left: 15px;
      // bottom: 10px;
      color: #666;
      font-size: 50px;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .person {
      position: absolute;
      left: 0;
      top: 0;
      // width: 500px;
      // height: 500px;
    }

    .bg {
      // width: 500px;
      // height: 500px;
    }
  }

  .avatar-edit {
    width: 600px;
  }
}

.avatar-info {
  // width: 500px;
  border-radius: 10px;
  border: 1px solid #7abbff;
  padding: 20rpx;

  .name-editor {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .operate {
      flex: 1;
    }

    .input-box {
      // width: 180px;
      flex: 2;
      border-radius: 6rpx;
      padding: 14rpx 6rpx;
      text-align: center;
      font-weight: bold;
    }
  }

  .scrollbar-flex-content {
    max-width: 350px;
    overflow-x: scroll;
    display: flex;
    padding: 10px 20px;
    border: 1px solid #f0f0f0;
    border-radius: 16rpx;

    .picker-item {
      margin: 0 5px;
      height: 80px;
      width: 80px;
      position: relative;
      border: 1px solid #f1f1f1;
      z-index: 1;
      display: inline-block;
    }

    .name {
      margin-top: 10px;
      font-size: 12px;
      color: #333;
      text-align: center;
    }

    .acitve {
      box-shadow: 0px 0px 2px 2px #ffca6b;
      z-index: 2;
    }
  }
}

.publish-wrap_inner-container {
  margin-left: 20rpx;
  padding: 20rpx;
  border: 1px solid #7abbff;
  border-radius: 16rpx;
}

.flex-column {
  display: flex;
  flex-direction: column;
}
</style>